package com.lz.sports.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import androidx.annotation.NonNull
import com.github.mjdev.libaums.fs.UsbFile
import com.lz.sports.R
import com.lz.sports.core.ProjectManager
import com.lz.sports.utils.ImportsUtils
import kotlinx.coroutines.*
import java.io.File

/**
 * UsbFile拷贝
 */
class UsbCopyDialog(@NonNull context: Context, private val usbFile: UsbFile, private val dir: File) :
    Dialog(context, com.lz.library.R.style.lib_dialogTheme) {

    private val mainScope = MainScope()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_usb_copy)
        setCanceledOnTouchOutside(false)
        this.window!!.setBackgroundDrawableResource(com.lz.library.R.drawable.lib_bg_pbloading)

        mainScope.launch {
            ProjectManager.clear()
            val job = async(Dispatchers.IO) {
                ImportsUtils.importsZip(usbFile, dir)
            }
            val res = ProjectManager.from(job.await())
            onCopiedListener?.onCopied(res)
            dismiss()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) return true
        return super.onKeyDown(keyCode, event)
    }

    override fun dismiss() {
        super.dismiss()
        mainScope.cancel()
    }

    var onCopiedListener: OnCopiedListener? = null

    interface OnCopiedListener {

        fun onCopied(isSuccess: Boolean)
    }
}